﻿/**************************************************************
 * Copyright Eastmoney Corporation. All rights reserved.
 * 
 * Author: guitao(guitao@eastmoney.com) 
 * Create Date: 2020/6/15 13:17:25
 * Description:
 *          
 * Revision History:
 *      Date         Author               Description
 *              
***************************************************************/

using gt.EventBus.Abstractions;
using gt.EventBus.Events;
using System;
using System.Collections.Generic;
using System.Text;

namespace gt.EventBus
{
    public class InMemoryEventBus : IEventBus
    {
        private readonly IEventBusSubscriptionsManager _subcriptionManager;

        public InMemoryEventBus()
        {
            _subcriptionManager = new InMemoryEventBusSubscriptionsManager(); ;
        }


        public void Publish(IntegrationEvent @event)
        {
            var eventType = @event.GetType();
            var handlerTypes = _subcriptionManager.GetHandlersForEvent(eventType.Name);
            foreach (var handlerType in handlerTypes)
            {
                //IIntegrationEventHandler<IntegrationEvent> handler = Activator.CreateInstance(handlerType) as IIntegrationEventHandler<IntegrationEvent>;
                //handler.Handle(@event);

                var method = handlerType.GetMethod("Handle");
                var instance = Activator.CreateInstance(handlerType);
                method.Invoke(instance, new object[] { @event });
            }
        }

        public void Subscribe<T, TH>()
            where T : IntegrationEvent
            where TH : IIntegrationEventHandler<T>
        {
            _subcriptionManager.AddSubscription<T, TH>();
        }

        public void Unsubscribe<T, TH>()
            where T : IntegrationEvent
            where TH : IIntegrationEventHandler<T>
        {
            _subcriptionManager.RemoveSubscription<T, TH>();
        }
    }
}
